<template>
  <div class="container">
    <!-- 左侧树结构 -->
    <div class="tree-container">
      <a-tree
        :tree-data="treeData"
        :replaceFields="{ children: 'children', title: 'title', key: 'key' }"
        @select="handleSelect"
        :default-expand-all="true"
      />
    </div>

    <!-- 新增右侧表格 -->
    <div class="table-container">
      <a-table
        :data-source="deviceData"
        :columns="columns"
        :pagination="false"
        bordered
        size="middle"
        :row-class-name="(_record, index) => (index === selectedRowIndex ? 'selected-row' : '')"
        @rowClick="handleRowClick"
      >
        <template #status="{ text }">
          <a-tag :color="statusColorMap[text]">{{ text }}</a-tag>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive } from 'vue';
  import type { TreeProps } from 'ant-design-vue';
  import { convertToTreeData } from './treeUtils';
  import { getDeviceTree } from './dataApplication.api';
  // 响应式状态
  const treeData = ref<TreeProps['treeData']>([]);
  const selectedPath = ref<Record<string, any>>({});

  // 模拟API请求
  const fetchData = async () => {
    const res = await getDeviceTree();
    console.log(res, 'result');
    treeData.value = convertToTreeData(res.deviceOneList);
  };

  // 处理节点选中
  /*  const handleSelect: TreeProps['onSelect'] = (selectedKeys, { node }) => {
    if (node.level !== 4) return;

    // 新方法：通过树数据遍历获取完整路径
    const findParentKeys = (tree: TreeProps['treeData'], key: string, path: string[] = []): string[] => {
      for (const item of tree || []) {
        if (item?.key === key) return path;
        if (item?.children) {
          const found = findParentKeys(item.children, key, [...path, item.key]);
          if (found) return found;
        }
      }
      return [];
    };

    const parentKeys = findParentKeys(treeData.value, node.key);
    const getNodeByKey = (key: string) => {
      const stack = [...treeData.value];
      while (stack.length) {
        const node = stack.pop();
        if (node?.key === key) return node;
        node?.children?.forEach((child) => stack.push(child));
      }
    };

    const pathData = {
      level4: node.rawData,
      level3: getNodeByKey(parentKeys[2]),
      level2: getNodeByKey(parentKeys[1]),
      level1: getNodeByKey(parentKeys[0]),
    };

    console.log('修正后的pathData:', pathData);
    submitToBackend(pathData);
  }; */
  // 处理节点选中
  const handleSelect = (selectedKeys, { node }) => {
    // 只处理第五层节点（键值对）
    if (node.level !== 5) return;
    // 向上追溯获取完整路径
    const pathData = {
      level5: node.rawData, // 键值对
      level4: node.parent.rawData, // data对象
      level3: node.parent.parent.rawData, // 设备详情
      level2: node.parent.parent.parent.rawData, // 设备ID
      level1: node.parent.parent.parent.parent.rawData, // 设备标记
    };

    selectedPath.value = pathData;
    submitToBackend(pathData);
  };

  // 提交到后端
  const submitToBackend = (data: typeof selectedPath.value) => {
    console.log('提交完整路径数据:', data);
    // 实际提交逻辑
    // api.submitSelectedData(data).then(...)
  };

  // 生命周期钩子
  onMounted(fetchData);

  // 新增表格数据
  const deviceData = reactive([
    { id: 1, deviceNo: 'SC-001', name: '生产设备A', status: '正常', lastUpdate: '2024-05-20 09:00' },
    { id: 2, deviceNo: 'JC-002', name: '检测设备B', status: '预警', lastUpdate: '2024-05-20 09:15' },
    { id: 3, deviceNo: 'BZ-003', name: '包装设备C', status: '故障', lastUpdate: '2024-05-20 09:30' },
  ]);
  /* 设备一级分类	设备二级分类	设备三级级分类	规则详情	需要处理字段	操作 */
  const columns = ref([
    { title: '设备一级分类', dataIndex: 'deviceNo', width: 120 },
    { title: '设备二级分类', dataIndex: 'name', ellipsis: true }, // 添加自动省略
    { title: '设备三级级分类', dataIndex: 'status', slots: { customRender: 'status' }, width: 100 },
    { title: '最后上报', dataIndex: 'lastUpdate', width: 180, align: 'right' }, // 右对齐时间
  ]);

  const statusColorMap = {
    正常: '#52c41a',
    预警: '#faad14',
    故障: '#ff4d4f',
  };

  const selectedRowIndex = ref<number>(0);

  const handleRowClick = (record: any, index: number) => {
    selectedRowIndex.value = index;
    // 触发树形结构更新
    fetchData(record.id);
  };
</script>

<style scoped lang="less">
  .container {
    display: flex;
    width: 100%;
    min-width: 100%;
    padding: 16px;
    background: #fff;
    box-sizing: border-box;

    .tree-container {
      width: 35%;
      margin-right: 16px;
      :deep(.ant-tree) {
        padding: 30px !important;
        // 使用Ant Design官方推荐的嵌套方式
        .ant-tree-treenode {
          margin: 4px 0 !important;
          .ant-tree-node-content-wrapper {
            padding: 4px 8px !important;
          }
          .ant-tree-switcher {
            line-height: 30px;
          }
        }
      }
    }

    .table-container {
      flex: 1;
      min-width: calc(65% - 16px);
      display: flex;
      flex-direction: column;
      overflow: hidden;
      :deep(.ant-table) {
        flex: 1;
        display: flex;
        flex-direction: column;

        .ant-table-container {
          flex: 1;
          display: flex;
          flex-direction: column;

          .ant-table-body {
            flex: 1;
            overflow: auto !important;
          }
        }

        .ant-table-tbody > tr.selected-row {
          background-color: #e6f7ff;
          td {
            background-color: transparent;
          }
        }
        .ant-table-tbody > tr:hover {
          cursor: pointer;
          background-color: #fafafa;
        }
      }
    }
  }
</style>
